package com.cuanbo.dualscreenteachfu.service;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.core.app.NotificationCompat;

import com.cuanbo.dualscreenteachfu.base.App;
import com.cuanbo.dualscreenteachfu.bean.ConfigInfo;
import com.cuanbo.dualscreenteachfu.constant.MatrixConstant;
import com.cuanbo.dualscreenteachfu.http.HttpWebServerCheck;
import com.cuanbo.dualscreenteachfu.matrix.MatrixInitThread;
import com.cuanbo.dualscreenteachfu.receiver.CbReceiver;
import com.cuanbo.dualscreenteachfu.receiver.MatrixBroadcastReceiver;
import com.cuanbo.dualscreenteachfu.utils.AppUtil;
import com.cuanbo.dualscreenteachfu.utils.ConnectStateUtil;
import com.cuanbo.dualscreenteachfu.utils.DevStateUtil;
import com.cuanbo.dualscreenteachfu.utils.IpUtil;
import com.cuanbo.dualscreenteachfu.utils.LogUtil;
import com.cuanbo.dualscreenteachfu.utils.SharedPreferencesUtil;

import java.util.Date;

public class BackgroundService extends Service implements MatrixBroadcastReceiver.MatrixListener {
    private int num=0;
    private CbReceiver cbReceiver;
    public static boolean reConnectingMatrix=false;
    private MatrixBroadcastReceiver matrixBroadcastReceiver;
    private long oldReTimeMatrix;
    private MatrixInitThread matrixTcpInitThread;
    private static Object lock = new Object();
    private Handler myHandler;
    //矩阵重连消息
    public static int MSG_MATRIX_RECONNECT = 1;

    @Override
    public void onCreate() {
        super.onCreate();
        matrixTcpInitThread = new MatrixInitThread(App.configInfo.getMatrixIP(), App.configInfo.getMatrixPort());
        matrixTcpInitThread.start();
        myHandler = new Handler(getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MSG_MATRIX_RECONNECT) {
                    if (App.matrixIPNetState) {
                        reConnectMatrix();
                    }
                }
            }
        };
        registerReceiver(matrixBroadcastReceiver = new MatrixBroadcastReceiver(this), new IntentFilter(MatrixConstant.MATRIX_ACTION));
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        notification();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (App.running) {
                    work();
                    num++;
                    if (num == Long.MAX_VALUE) {
                        num = 0;
                    }
                    try{
                        Thread.sleep(1000);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(cbReceiver);
        unregisterReceiver(matrixBroadcastReceiver);
    }

    /**
     * 后台运行需要在通知栏提醒，否则会报错
     */
    public void notification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.createNotificationChannel(new NotificationChannel("42", "智慧教学机", NotificationManager.IMPORTANCE_DEFAULT));
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "42");
            startForeground(2, builder.build());
        }
    }

    public static long getDataRecordTime=0;

    private void work() {
        //每隔60秒检查一次web服务器访问是否异常
        if (num != 0 && num % 60 == 0) {
            new HttpWebServerCheck().request();
        }
        //中控IP网络检查
        if(!App.configInfo.isMatrixState()){
            IpUtil.checkMatrixIPPing();
        }
        //每隔一段时间拉起自己显示到前台
        AppUtil.timer(this);
        ConnectStateUtil.checkConnectStateMatrix(App.getInstance(), MatrixConstant.KEY_MATRIX, ConnectStateUtil.timeoutMatrixInitiative);
    }

    /**
     *重连中控
     */
    public void reConnectMatrix() {
        long nowReTime = new Date().getTime();
        long diff = nowReTime - oldReTimeMatrix;
        if (diff < 5000) {
            return;
        }
        oldReTimeMatrix = nowReTime;
        App.configInfo.setMatrixState(false);
        LogUtil.add("状态", "将网络状态设置为false(BackgroundServiceHelper 361)", "中控网络", false);
        ConfigInfo configInfo = (ConfigInfo) SharedPreferencesUtil.getBean(App.getInstance(), ConfigInfo.class);
        if (configInfo != null && configInfo.isMatrixState() == true) {
            SharedPreferencesUtil.saveBean(App.getInstance(), App.configInfo);
        }
        if (App.configInfo.getMatrixIP() == null || App.configInfo.getMatrixIP().equals("")) {
            reConnectingMatrix = false;
            if (matrixTcpInitThread != null) {
                matrixTcpInitThread.close();
                LogUtil.add("BackgroundServiceHelper(548)","matrixTcpInitThread.close()","关闭中控Tcp");
                matrixTcpInitThread = null;
            }
            return;
        }
        LogUtil.add("尝试重连", "reConnectingMatrix=" + reConnectingMatrix + " matrixTcpInitThread=" + matrixTcpInitThread, "矩阵");
        synchronized (lock) {
            if (!reConnectingMatrix) {
                reConnectingMatrix = true;
                if (matrixTcpInitThread != null) {
                    matrixTcpInitThread.close();
                    LogUtil.add("BackgroundServiceHelper(559)","matrixTcpInitThread.close()","关闭中控Tcp");
                    matrixTcpInitThread = null;
                }
                matrixTcpInitThread = new MatrixInitThread(App.configInfo.getMatrixIP(), App.configInfo.getMatrixPort());
                matrixTcpInitThread.start();
            }
        }
    }

    @Override
    public void initConnectSuccess() {
        App.configInfo.setMatrixState(true);
        LogUtil.add("状态", "将网络状态设置为true", "中控网络", false);
        SharedPreferencesUtil.saveBean(getApplicationContext(), App.configInfo);
    }

    @Override
    public void initConnectFail() {
        App.configInfo.setMatrixState(false);
        LogUtil.add("状态", "将网络状态设置为false", "中控网络", false);
        SharedPreferencesUtil.saveBean(getApplicationContext(), App.configInfo);
        reConnect();
    }

    @Override
    public void initError() {
        App.configInfo.setMatrixState(false);
        LogUtil.add("状态", "将网络状态设置为false", "中控网络", false);
        SharedPreferencesUtil.saveBean(getApplicationContext(), App.configInfo);
        reConnect();
    }

    @Override
    public void receiveMsg(String msg) {

    }

    @Override
    public void receiveMsgFilter(String msg) {
        DevStateUtil.save(msg);
    }

    @Override
    public void receiveError() {
        App.configInfo.setMatrixState(false);
        LogUtil.add("状态", "将网络状态设置为false", "中控网络", false);
        ConfigInfo configInfo = (ConfigInfo) SharedPreferencesUtil.getBean(getApplicationContext(), ConfigInfo.class);
        if (configInfo != null && configInfo.isMatrixState() == true) {
            SharedPreferencesUtil.saveBean(getApplicationContext(), App.configInfo);
        }
        reConnect();
    }

    @Override
    public void reConnect() {
        myHandler.sendEmptyMessage(MSG_MATRIX_RECONNECT);
    }

    @Override
    public void sendError() {
        App.configInfo.setMatrixState(false);
        LogUtil.add("状态", "将网络状态设置为false", "中控网络", false);
        ConfigInfo configInfo = (ConfigInfo) SharedPreferencesUtil.getBean(getApplicationContext(), ConfigInfo.class);
        if (configInfo != null && configInfo.isMatrixState() == true) {
            SharedPreferencesUtil.saveBean(getApplicationContext(), App.configInfo);
        }
        reConnect();
    }

    @Override
    public void classTimer() {

    }

    @Override
    public void reConnectTimer() {

    }

    @Override
    public void unConnectMatrixIp() {
        App.configInfo.setMatrixState(false);
    }

}
